package com.zhb.service.impl;

import com.zhb.entity.Order;
import com.zhb.entity.OrderDto;
import com.zhb.feign.AccountFeign;
import com.zhb.feign.ProductFeign;
import com.zhb.mapper.OrderMapper;
import com.zhb.service.IOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhb
 * @since 2021-09-09
 */
@Service
@AllArgsConstructor
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    private final AccountFeign accountFeign;
    private final ProductFeign productFeign;

    @Override
    @GlobalTransactional(name = "createOrder", rollbackFor = Exception.class)
    public void createOrder(OrderDto orderDTO) {
        Order order = new Order();
        BeanUtils.copyProperties(orderDTO,order);
        //本地存储Order
        this.save(order);
        String xid = RootContext.getXID();
        log.error(xid);
        //库存扣减
        productFeign.deduct(orderDTO.getProductCode(),order.getCount());
        //账户余额扣减
        accountFeign.reduce(orderDTO.getAccountCode(), orderDTO.getAmount());
    }
}
